<?php

/**
 * This is the model class for table "{{category}}".
 *
 * The followings are the available columns in table '{{category}}':
 * @property integer $id
 * @property string $name
 * @property string $create_time
 * @property string $update_time
 * @property string $tags
 * @property string $status
 * @property string $access
 * @property integer $create_user_id
 * @property integer $update_user_id
 *
 * The followings are the available model relations:
 * @property Article[] $articles
 * @property User $createUser
 * @property User $updateUser
 */
class Category extends CategoryActiveRecord
{
    public $record_counts;
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{category}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name, tags,access,status', 'required'),
			array('create_user_id, update_user_id,access,status', 'numerical', 'integerOnly'=>true),
			array('name,tags', 'length', 'min'=>3, 'max'=>255),
			array('create_time, update_time', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, name, create_time, update_time, tags, create_user_id, update_user_id,access,status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'articles' => array(self::HAS_MANY, 'Article', 'category_id'),
			'createUser' => array(self::BELONGS_TO, 'User', 'create_user_id'),
			'updateUser' => array(self::BELONGS_TO, 'User', 'update_user_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => Yii::t('CategoryModule.base','Name'),
			'create_time' => Yii::t('CategoryModule.base','Create Time'),
			'update_time' => Yii::t('CategoryModule.base','Update Time'),
			'tags' => Yii::t('CategoryModule.base','Tags'),
			'create_user_id' => Yii::t('CategoryModule.base','Create User'),
			'update_user_id' => Yii::t('CategoryModule.base','Update User'),
             'record_counts'=>Yii::t('CategoryModule.base','Record Counts'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('status',$this->status,true);
		$criteria->compare('access',$this->access,true);
		$criteria->compare('tags',$this->tags,true);
		$criteria->compare('create_user_id',$this->create_user_id);


		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Category the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    //Возвращяем данные пользователя, который обновил,если они существуют.
    public function getUpdateUserData()
    {
        if($this->update_user_id)
        {
            $data = array();
            $data = CHtml::tag('span',array('class'=>'text-info'),Yii::t('CategoryModule.base','Name')).': '.CHtml::tag('b',array(),$this->updateUser->name).' | ';
            $data .= CHtml::tag('span',array('class'=>'text-info'),Yii::t('CategoryModule.base','Login')).': '.CHtml::tag('b',array(),$this->updateUser->login).' | ';
            $data .= CHtml::tag('span',array('class'=>'text-info'),Yii::t('CategoryModule.base','Role')).': '.CHtml::tag('b',array(),$this->updateUser->role);
            return $data;
        }
        else
        {
            return CHtml::tag('span',array('class'=>'label label-info','style'=>'line-height:2'),Yii::t('CategoryModule.base','Has not been updated'));
        }
    }

    //Возвращяем данные пользователя, который обновил,если они существуют.
    public function getCreateUserData()
    {
        if($this->create_user_id)
        {
            $data = array();
            $data = CHtml::tag('span',array('class'=>'text-info'),Yii::t('CategoryModule.base','Name')).': '.CHtml::tag('b',array(),$this->createUser->name).' | ';
            $data .= CHtml::tag('span',array('class'=>'text-info'),Yii::t('CategoryModule.base','Login')).': '.CHtml::tag('b',array(),$this->createUser->login).' | ';
            $data .= CHtml::tag('span',array('class'=>'text-info'),Yii::t('CategoryModule.base','Role')).': '.CHtml::tag('b',array(),$this->createUser->role);
            return $data;
        }
        else
        {
            return Yii::t('ArticleModule.base','Undefined');
        }
    }

    //Возвращяем отформтированную дату и время создания
    public function getCreateDateTimeFormat()
    {
        if(isset($this->create_time))
        {
            return CHtml::tag('span',array('class'=>'label label-primary'),CLocale::getInstance(Yii::app()->getLocale()->id)->dateFormatter->formatDateTime(strtotime($this->create_time),'long','short'));
        }
        return CHtml::tag('span',array('class'=>'label label-danger','style'=>'line-height:2'),Yii::t('CategoryModule.base','Undefined'));
    }
    //Возвращяем отформтированную дату и время обновления
    public function getUpdateDateTimeFormat()
    {
        if(isset($this->update_time))
        {
            if(strtotime($this->create_time) === strtotime($this->update_time))
            {
                return CHtml::tag('span',array('class'=>'label label-info','style'=>'line-height:2'),Yii::t('CategoryModule.base','Has not been updated'));
            }
            return CLocale::getInstance(Yii::app()->getLocale()->id)->dateFormatter->formatDateTime(strtotime($this->update_time),'long','short');
        }
        return CHtml::tag('span',array('class'=>'label label-danger','style'=>'line-height:2'),Yii::t('CategoryModule.base','Undefined'));
    }

    //
    public function getRecordCount()
    {
       $article = new Article();
        $articles_count = $article->findAllByAttributes(array('category_id'=>$this->id));
       return count($articles_count);
    }

    //Отдаем уровни доступа
    public function getAccessStatus()
    {
        return  array('1'=>'Guest','2'=>'Public','3'=>'Registered','4'=>'Special');
    }

    //Отдаем статус категории
    public function getStatus()
    {
        return  array('1'=>'Guest','2'=>'Public','3'=>'Registered','4'=>'Special');
    }

    //Отдаем статус категории в виде иконки
    public function getStatusIcon()
    {
        if($this->status)
        {
            return CHtml::image(Yii::app()->theme->baseUrl.'/assets/gridview/yes.png',Yii::t('ArticleModule.base','Published'),array('title'=>Yii::t('ArticleModule.base','Published')));
        }
        else
        {
            return CHtml::image(Yii::app()->theme->baseUrl.'/assets/gridview/no.png',Yii::t('ArticleModule.base','Not published'),array('title'=>Yii::t('ArticleModule.base','Not published')));
        }
    }

    //Возвращаем статус категории
    public function getStatusOptions()
    {
        return array('0'=>Yii::t('CategoryModule.base','No'),'1'=>Yii::t('CategoryModule.base','Yes'));
    }
}
